﻿jQuery.extend({
    //------金额输入框初始化
    cashInput: function () {
        //控制输入框只能输入数字和小数点
        $(".ci").live("keyup", function () {
            var pos = $(this).Cposition(); //获得光标位置
            var temp = $(this).val().length; //保存原始值
            $.limit($(this)); //动态修改金额样式
            pos = pos - (temp - $(this).val().length); //当前光标位置
            $(this).Cposition(pos); //设置光标位置
        });
        $(".ci").live("focus", function () {
            //$.format($(this));
        });
        $(".ci").live("blur", function () {
            $(this).val(fmoney($(this).val(), 2));
            //$.zero($(this));
            //$.removeZero($(this), $(this).val());
        });
    },
    limit: function (arg) {
        var limitV = $(arg).val();
        if (limitV) {
            $(arg).val(limitV.replace(/[^0-9.-]/g, ""));
            $.format($(arg));
        }
    },
    format: function (arg) {
        var formatV = $(arg).val();
        var array = new Array();
        array = formatV.split(".");
        var re = /(-?\d+)(\d{3})/;
        while (re.test(array[0])) {
            if (array[0]) {
                array[0] = array[0].replace(re, "$1,$2");
            }
        }
        var returnV = array[0];
        for (var i = 1; i < array.length; i++) {
            returnV += "." + array[i];
        }
        $(arg).val(returnV);
    },
    unformat: function (arg) {
        var v = $(arg).val();
        var x = v.split(',');
        var returnV = parseFloat(x.join(""));
        $(arg).val(returnV);
    },
    zero: function (arg) {
        var val = $(arg).val();
        if (!val) {
            return false;
        }
        if (val.indexOf(".") == 0) {
            $(arg).val("");
        }
        else {
            if (val.indexOf(".") < 0) {
                $(arg).val(val + ".00");
            }
            else {
                var xs = val.split(".")[1];
                if (xs) {
                    if (xs.length < 2) {
                        $(arg).val(val + "0");
                    }
                }
                else {
                    $(arg).val(val + "00");
                }
            }
        }
    },
    removeZero: function (arg, val) {
        if (val.indexOf("0.") != 0 && (val.indexOf("0") == 0 || val.indexOf(",") == 0)) {
            val = val.substring(1);
            $.removeZero($(arg), val);
        } else {
            $(arg).val(val);
        }
    }
});


//初始化金额输入框
$.cashInput();

/**
* 将数值四舍五入(保留2位小数)后格式化成金额形式
*
* @param num 数值(Number或者String)
* @return 金额格式的字符串,如'1,234,567.45'
* @type String
*/
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
            num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
}

// 格式化金额
function fmoney(s, n) {
    if (s == null || s == "") return 0;
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for (i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
}
// 金额还原
function rmoney(s) {
    return parseFloat(s.replace(/[^\d\.-]/g, ""));
}

$.fn.extend({
    Cposition: function (value) {
        var elem = this[0];
        if (elem && (elem.tagName == "TEXTAREA" || (elem.type && elem.type.toLowerCase() == "text"))) {
            if ($.browser.msie) {
                var rng;
                if (elem.tagName == "TEXTAREA") {
                    rng = event.srcElement.createTextRange();
                    rng.moveToPoint(event.x, event.y);
                } else {
                    rng = document.selection.createRange();
                }
                if (value === undefined) {
                    rng.moveStart("character", -event.srcElement.value.length);
                    return rng.text.length;
                } else if (typeof value === "number") {
                    var index = this.position();
                    index > value ? (rng.moveEnd("character", value - index)) : (rng.moveStart("character", value - index))
                    rng.select();
                }
            } else {
                if (value === undefined) {
                    return elem.selectionStart;
                } else if (typeof value === "number") {
                    elem.selectionEnd = value;
                    elem.selectionStart = value;
                }
            }
        } else {
            if (value === undefined)
                return undefined;
        }
    }
})